﻿using CommonClass;
using I_Produce.Domains.DTO;
using I_Produce.Domains.Entity;
using I_Produce.Infrastructure.Interface;
using I_Produce.Read.API.Application.Commands.SeedBirthCommand;
using MediatR;

namespace I_Produce.Read.API.Application.CommandHandlers.SeedBirthHandler
{
	public class SeedBirthQueryCommandHandler : IRequestHandler<SeedBirthQueryCommand, ApiResult<PagerResult<SeedBirth>>>
	{
		private readonly ISeedBirthRepository _repository;

		public SeedBirthQueryCommandHandler(ISeedBirthRepository seedBirthRepository)
		{
			_repository = seedBirthRepository;
		}

		public async Task<ApiResult<PagerResult<SeedBirth>>> Handle(SeedBirthQueryCommand request, CancellationToken cancellationToken)
		{
			var list = _repository.All().Result.Where(x => !x.IsDel);

			if (!string.IsNullOrEmpty(request.sDeliveryDate))
			{
				list = list.Where(x => x.DeliveryDate >= DateTime.Parse(request.sDeliveryDate));
			}

			if (!string.IsNullOrEmpty(request.eDeliveryDate))
			{
				list = list.Where(x => x.DeliveryDate < DateTime.Parse(request.eDeliveryDate).AddDays(1));
			}

			if (!string.IsNullOrEmpty(request.motherEarHorn))
			{
				list = list.Where(x => x.MotherEarHorn.Contains(request.motherEarHorn));
			}

			if (!string.IsNullOrEmpty(request.currentBuilding))
			{
				list = list.Where(x => x.CurrentBuilding.Equals(request.currentBuilding));
			}

			if (!string.IsNullOrEmpty(request.transferBuilding))
			{
				list = list.Where(x => x.TransferBuilding.Contains(request.transferBuilding));
			}

			if (!string.IsNullOrEmpty(request.broodNumber))
			{
				list = list.Where(x => x.BroodNumber.Contains(request.broodNumber));
			}

			if (!string.IsNullOrEmpty(request.personCharge))
			{
				list = list.Where(x => x.PersonCharge.Contains(request.personCharge));
			}

			var total = list.Count();
			var page = (int)Math.Ceiling(total * 1.0 / request.pageSize);

			list = list.OrderByDescending(x => x.Id).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize);

			return new ApiResult<PagerResult<SeedBirth>>
			{
				Code = 200,
				msg = "成功",
				Data = new PagerResult<SeedBirth>
				{
					TotalCount = total,
					PageCount = page,
					Datas = list.ToList()
				}
			};
		}
	}
}
